<?php


namespace App\Http\Controllers\Api;


use App\Http\Controllers\Controller;
use App\Models\Address;
use App\Models\Classification;
use App\Models\Commodity;
use App\Models\CommodityOrder;
use App\Models\CommodityOrderComment;
use App\Models\CommodityOrderDetail;
use App\Models\CustomerSessionInfo;
use App\Models\GoodsClass;
use App\Models\GoodsSku;
use App\Models\GoodsSpu;
use App\Models\GroupBuy;
use App\Models\ShopCart;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class CommodityController extends Controller
{
    public $internalPaymentSn;

    public function goodsClass(Request $request)
    {
        $classId = $request->input('class_id');

        $goodsClass = GoodsClass::with('spu');
        if ($classId) {
            $goodsClass->where('id', $classId);
        }
        $data = $goodsClass->get();
        return $this->makeResponse($data, '查询成功', 200);
    }

    public function goodsDetail(Request $request)
    {
        $spuId = $request->input('spu_id', 0);
        $data = GoodsSpu::with('sku')->find($spuId);

        $data->comment = CommodityOrderComment::with(['customer' => function ($query) {
            $query->select('id', 'nick_name', 'avatar_url');
        }])->where('spu_id', $spuId)->limit(1)->get();
        $data->comment_count = CommodityOrderComment::where('spu_id', $spuId)->count();

        $recommend = GoodsSpu::where('id','<>', $spuId)->select('id','spu_name','price','activity_price','commodity_image_thum')-> limit(3)->get();

        $data->recommend = $recommend;
        if (!$data) {
            return $this->makeResponse([], '查询失败', 404);
        }
        return $this->makeResponse($data, '查询成功', 200);

    }


    /**
     * 购物车创建订单
     * @param Request $request
     * @return array
     */
    public function createOrderByShopCart(Request $request)
    {
        DB::beginTransaction();
        $requests = $request->all();
        $user = $request->user();

        $cartIds = json_decode($requests['cart_ids'], true); // 购物车id
        $carts = ShopCart::with('sku', 'spu', 'shop')->whereIn('id', $cartIds)->get();

        $arr = [];
        $data = $this->recombination($carts, $arr); // 按店铺重组数组

        // 删除购物车信息
        if (!ShopCart::destroy($cartIds)) {
            DB::rollBack();
            return makeResponse(['internal_payment_sn' => $this->internalPaymentSn], '创建订单失败～', 500);
        }

        // 创建订单
        if ($this->createOrderProcess($data, $user, $requests)) {
            DB::commit();
            return makeResponse(['internal_payment_sn' => $this->internalPaymentSn], '创建订单成功～', 201);
        } else {
            DB::rollBack();
            return makeResponse(['internal_payment_sn' => $this->internalPaymentSn], '创建订单失败～', 500);
        }
    }

    /**
     * @param $v
     * @param array $orderDetails
     * @param $k
     * @param static $orderModel
     * @param $price
     * @return array
     */
    public function orderDetails($v, array $orderDetails, $k, $orderModel, $price): array
    {
        $orderDetails[$k]['spu_id'] = $v['spu']['id'];
        $orderDetails[$k]['spu_name'] = $v['spu']['spu_name'];
        $orderDetails[$k]['shop_id'] = $v['spu']['shop_id'];
        $orderDetails[$k]['number'] = $v['number'];
        $orderDetails[$k]['sku_id'] = $v['sku']['id'];
        $orderDetails[$k]['sku_name'] = $v['sku']['sku_name'];
        $orderDetails[$k]['original_price'] = $v['sku']['activity_price'];
        $orderDetails[$k]['order_id'] = $orderModel->id;
        $orderDetails[$k]['total_price'] = $price;
        return $orderDetails;
    }

    /**
     * @param $carts
     * @param array $data
     * @return array
     */
    public function recombination($carts, array $data): array
    {
        foreach ($carts as $key => $value) {
            $data[$value['shop_id']]['sub'][] = $value->toArray();
        }
        return $data;
    }

    /**
     * @param array $data
     * @param $user
     * @return array
     */
    public function createOrderProcess(array $data, $user, array $requests): bool
    {
        $address = Address::find((int)$requests['address_id']);
        $this->internalPaymentSn = self::createSn();
        foreach ($data as $key => $value) {
            $orderModel = CommodityOrder::createOne([
                'internal_order_sn' => self::createSn(),
                'customer_id' => $user['id'],
                'internal_payment_sn' => $this->internalPaymentSn,
                'contacts' => $address['contacts'],
                'mobile' => $address['phone'],
                'full_address' => $address->province . $address->city . $address->area . $address->full_address,
                'shop_id' => $key,
                'is_default_address' => $address->is_default
            ]);
            $result = $orderModel->save();

            if (!$result) {
                return false;
            }
            $totalPrice = 0;
            foreach ($value['sub'] as $k => $v) {
                $orderDetails = [];
                $price = $v['number'] * $v['sku']['activity_price'];
                $orderDetails = $this->orderDetails($v, $orderDetails, $k, $orderModel, $price);
                $totalPrice += $price;
                if (!CommodityOrderDetail::insert($orderDetails)) {
                    return false;
                }
            }
            $result = CommodityOrder::where('id', $orderModel->id)->update(['order_total_price' => $totalPrice]);
            if (!$result) {
                return false;
            }
        }
        return true;
    }

    /**
     * 拼团商品详情的团列表
     * @param Request $request
     * @param $id
     * @return array
     */
    public function groupBuyList(Request $request, $id)
    {
        $groupBuys = GroupBuy::where('spu_id',
            $id)->whereRaw('total_number > join_number')->orderByDesc('id')->limit(2)->get();
        foreach ($groupBuys as $key => $value) {
            $ids = explode(',', $value->user_ids);
            $value->users = CustomerSessionInfo::whereIn('id', $ids)->get(['nick_name', 'avatar_url'])->toArray();
        }
        return makeResponse($groupBuys, 'success', 200);
    }

    /**
     * 首页的拼团
     * @return array
     */
    public function groupBuyCommodityList()
    {
        $list = GoodsSpu::where('is_group_buy', 1)->orderBy('end_time')->limit(3)->get();
        return makeResponse($list, 'success', 200);
    }

    public function groupBuyArea(Request $request)
    {
        $groupBuyType = $request->input('group_buy_type');
        $skip = ($request->page - 1) * $request->size;
        $query = GoodsSpu::query();
        if ($groupBuyType) {
            $query->where('group_buy_type', $groupBuyType);
        }
        $list = $query->where([
            'is_group_buy' => 1
        ])->skip($skip)->take($request->size)->get();

        return makeResponse($list, 'success', 200);
    }
}